/**
 * Boss - Boss实体类
 * 继承Entity，实现Boss战中的敌人逻辑和AI行为
 */

import { Entity, EntityType, type EntityOptions } from './Entity'
import type { Vector2D } from './GameEngine'
import type { Player } from './Player'

export enum BossType {
  GUARDIAN = 'guardian',     // 守护者Boss - 基础Boss
  DESTROYER = 'destroyer',   // 毁灭者Boss - 攻击型Boss
  PHANTOM = 'phantom'        // 幻影Boss - 移动型Boss
}

export enum BossState {
  IDLE = 'idle',           // 空闲状态
  PATROL = 'patrol',       // 巡逻状态
  CHASE = 'chase',         // 追击状态
  ATTACK = 'attack',       // 攻击状态
  STUNNED = 'stunned',     // 眩晕状态
  DEFEATED = 'defeated'    // 被击败状态
}

export enum AttackPattern {
  PROJECTILE = 'projectile',   // 发射弹幕
  CHARGE = 'charge',           // 冲撞攻击
  AREA = 'area',               // 范围攻击
  SUMMON = 'summon'            // 召唤小怪
}

export interface BossAttack {
  pattern: AttackPattern
  damage: number
  cooldown: number          // 攻击冷却时间(ms)
  range: number            // 攻击范围
  duration: number         // 攻击持续时间(ms)
  projectileSpeed?: number // 弹幕速度
  projectileCount?: number // 弹幕数量
}

export interface BossOptions extends Omit<EntityOptions, 'type'> {
  bossType: BossType
  maxHealth?: number
  moveSpeed?: number
  detectionRange?: number
  attacks?: BossAttack[]
  phaseThresholds?: number[] // 血量阶段阈值
}

export interface BossPhase {
  healthThreshold: number  // 触发阶段的血量百分比
  moveSpeedMultiplier: number
  attackCooldownMultiplier: number
  newAttacks?: BossAttack[]
  specialBehavior?: string
}

export class Boss extends Entity {
  // Boss基础属性
  public readonly bossType: BossType
  public health: number
  public maxHealth: number
  public moveSpeed: number
  public detectionRange: number
  
  // 状态管理
  public state: BossState = BossState.IDLE
  public previousState: BossState = BossState.IDLE
  public currentPhase: number = 0
  public phases: BossPhase[]
  
  // 攻击系统
  public attacks: BossAttack[]
  public currentAttack: BossAttack | null = null
  public attackCooldownTimer: number = 0
  public attackDurationTimer: number = 0
  public lastAttackTime: number = 0
  
  // AI和目标追踪
  public target: Player | null = null
  public patrolStartX: number
  public patrolEndX: number
  public patrolDirection: number = 1
  public aggroTimer: number = 0
  public maxAggroTime: number = 10000 // 10秒后失去仇恨
  
  // 动画和视觉效果
  private stateChangeTime: number = 0
  private hitFlashTimer: number = 0
  private hitFlashDuration: number = 200 // ms
  
  // 弹幕系统
  public projectiles: BossProjectile[] = []
  
  constructor(options: BossOptions) {
    super({
      ...options,
      type: EntityType.BOSS // Boss使用专门的Boss类型
    })
    
    this.bossType = options.bossType
    this.maxHealth = options.maxHealth || this.getDefaultHealth()
    this.health = this.maxHealth
    this.moveSpeed = options.moveSpeed || this.getDefaultMoveSpeed()
    this.detectionRange = options.detectionRange || 300
    
    // 设置巡逻范围
    this.patrolStartX = this.x - 200
    this.patrolEndX = this.x + 200
    
    // 初始化攻击模式
    this.attacks = options.attacks || this.getDefaultAttacks()
    
    // 初始化阶段系统
    this.phases = this.initializePhases(options.phaseThresholds)
    
    // 设置初始状态
    this.changeState(BossState.PATROL)
  }
  
  /**
   * 更新Boss逻辑
   */
  update(deltaTime: number): void {
    if (!this.active || this.state === BossState.DEFEATED) {
      return
    }
    
    // 更新计时器
    this.updateTimers(deltaTime)
    
    // 更新AI状态机
    this.updateStateMachine(deltaTime)
    
    // 更新攻击系统
    this.updateAttackSystem(deltaTime)
    
    // 更新弹幕
    this.updateProjectiles(deltaTime)
    
    // 应用物理
    this.applyPhysics(deltaTime)
    
    // 检查阶段转换
    this.checkPhaseTransition()
    
    // 更新视觉效果
    this.updateVisualEffects(deltaTime)
  }
  
  /**
   * 设置目标玩家
   */
  setTarget(player: Player): void {
    this.target = player
    if (this.state === BossState.IDLE || this.state === BossState.PATROL) {
      this.changeState(BossState.CHASE)
    }
    this.aggroTimer = this.maxAggroTime
  }
  
  /**
   * 清除目标
   */
  clearTarget(): void {
    this.target = null
    this.aggroTimer = 0
    if (this.state === BossState.CHASE || this.state === BossState.ATTACK) {
      this.changeState(BossState.PATROL)
    }
  }
  
  /**
   * 受到伤害
   */
  takeDamage(damage: number): boolean {
    if (this.state === BossState.DEFEATED) {
      return false
    }
    
    this.health = Math.max(0, this.health - damage)
    this.hitFlashTimer = this.hitFlashDuration
    
    // 检查是否被击败
    if (this.health <= 0) {
      this.defeat()
      return true
    }
    
    // 如果没有目标且受到伤害，进入追击状态
    if (!this.target && this.state !== BossState.ATTACK) {
      this.changeState(BossState.CHASE)
    }
    
    return false
  }
  
  /**
   * 击败Boss
   */
  defeat(): void {
    this.changeState(BossState.DEFEATED)
    this.velocity.x = 0
    this.velocity.y = 0
    this.health = 0
    
    // 清理所有弹幕
    this.projectiles.forEach(projectile => projectile.destroy())
    this.projectiles = []
  }
  
  /**
   * 检查与玩家的距离
   */
  getDistanceToTarget(): number {
    if (!this.target) return Infinity
    
    const dx = this.target.x - this.x
    const dy = this.target.y - this.y
    return Math.sqrt(dx * dx + dy * dy)
  }
  
  /**
   * 检查目标是否在检测范围内
   */
  isTargetInRange(): boolean {
    return this.getDistanceToTarget() <= this.detectionRange
  }
  
  /**
   * 检查目标是否在攻击范围内
   */
  isTargetInAttackRange(): boolean {
    if (!this.currentAttack) return false
    return this.getDistanceToTarget() <= this.currentAttack.range
  }
  
  /**
   * 获取当前Boss状态信息
   */
  getStateInfo(): {
    bossType: BossType
    state: BossState
    health: number
    maxHealth: number
    currentPhase: number
    hasTarget: boolean
    attackCooldown: number
  } {
    return {
      bossType: this.bossType,
      state: this.state,
      health: this.health,
      maxHealth: this.maxHealth,
      currentPhase: this.currentPhase,
      hasTarget: this.target !== null,
      attackCooldown: this.attackCooldownTimer
    }
  }
  
  /**
   * 获取所有弹幕
   */
  getProjectiles(): BossProjectile[] {
    return [...this.projectiles]
  }
  
  /**
   * 改变状态
   */
  private changeState(newState: BossState): void {
    if (this.state !== newState) {
      this.previousState = this.state
      this.state = newState
      this.stateChangeTime = Date.now()
      
      // 状态进入时的特殊处理
      this.onStateEnter(newState)
    }
  }
  
  /**
   * 状态进入处理
   */
  private onStateEnter(state: BossState): void {
    switch (state) {
      case BossState.ATTACK:
        this.selectAttackPattern()
        break
      case BossState.STUNNED:
        this.velocity.x = 0
        this.velocity.y = 0
        break
      case BossState.DEFEATED:
        this.velocity.x = 0
        this.velocity.y = 0
        break
    }
  }
  
  /**
   * 更新计时器
   */
  private updateTimers(deltaTime: number): void {
    // 攻击冷却计时器
    if (this.attackCooldownTimer > 0) {
      this.attackCooldownTimer -= deltaTime
    }
    
    // 攻击持续时间计时器
    if (this.attackDurationTimer > 0) {
      this.attackDurationTimer -= deltaTime
    }
    
    // 仇恨计时器
    if (this.aggroTimer > 0) {
      this.aggroTimer -= deltaTime
      if (this.aggroTimer <= 0) {
        this.clearTarget()
      }
    }
    
    // 受击闪烁计时器
    if (this.hitFlashTimer > 0) {
      this.hitFlashTimer -= deltaTime
    }
  }
  
  /**
   * 更新AI状态机
   */
  private updateStateMachine(deltaTime: number): void {
    switch (this.state) {
      case BossState.IDLE:
        this.updateIdleState(deltaTime)
        break
      case BossState.PATROL:
        this.updatePatrolState(deltaTime)
        break
      case BossState.CHASE:
        this.updateChaseState(deltaTime)
        break
      case BossState.ATTACK:
        this.updateAttackState(deltaTime)
        break
      case BossState.STUNNED:
        this.updateStunnedState(deltaTime)
        break
      case BossState.DEFEATED:
        // 被击败状态不需要更新
        break
    }
  }
  
  /**
   * 更新空闲状态
   */
  private updateIdleState(deltaTime: number): void {
    this.velocity.x = 0
    
    // 检查是否有目标进入检测范围
    if (this.target && this.isTargetInRange()) {
      this.changeState(BossState.CHASE)
    } else {
      // 一段时间后开始巡逻
      if (Date.now() - this.stateChangeTime > 2000) {
        this.changeState(BossState.PATROL)
      }
    }
  }
  
  /**
   * 更新巡逻状态
   */
  private updatePatrolState(deltaTime: number): void {
    // 检查目标
    if (this.target && this.isTargetInRange()) {
      this.changeState(BossState.CHASE)
      return
    }
    
    // 巡逻移动
    this.velocity.x = this.moveSpeed * this.patrolDirection * 0.5 // 巡逻时速度减半
    
    // 检查巡逻边界
    if (this.patrolDirection > 0 && this.x >= this.patrolEndX) {
      this.patrolDirection = -1
    } else if (this.patrolDirection < 0 && this.x <= this.patrolStartX) {
      this.patrolDirection = 1
    }
  }
  
  /**
   * 更新追击状态
   */
  private updateChaseState(deltaTime: number): void {
    if (!this.target) {
      this.changeState(BossState.PATROL)
      return
    }
    
    // 检查是否失去目标
    if (!this.isTargetInRange()) {
      this.changeState(BossState.PATROL)
      return
    }
    
    // 移动向目标
    const dx = this.target.x - this.x
    const direction = Math.sign(dx)
    this.velocity.x = this.moveSpeed * direction
    
    // 检查是否可以攻击
    if (this.isTargetInAttackRange() && this.attackCooldownTimer <= 0) {
      this.changeState(BossState.ATTACK)
    }
  }
  
  /**
   * 更新攻击状态
   */
  private updateAttackState(deltaTime: number): void {
    this.velocity.x = 0 // 攻击时停止移动
    
    // 检查攻击是否结束
    if (this.attackDurationTimer <= 0) {
      this.changeState(BossState.CHASE)
    }
  }
  
  /**
   * 更新眩晕状态
   */
  private updateStunnedState(deltaTime: number): void {
    // 眩晕状态下不移动
    this.velocity.x = 0
    
    // 眩晕时间结束后恢复
    if (Date.now() - this.stateChangeTime > 1000) { // 1秒眩晕时间
      this.changeState(BossState.CHASE)
    }
  }
  
  /**
   * 更新攻击系统
   */
  private updateAttackSystem(deltaTime: number): void {
    if (this.state !== BossState.ATTACK || !this.currentAttack) {
      return
    }
    
    // 执行攻击
    this.executeAttack(deltaTime)
  }
  
  /**
   * 选择攻击模式
   */
  private selectAttackPattern(): void {
    if (this.attacks.length === 0) return
    
    // 根据当前阶段和距离选择合适的攻击
    const availableAttacks = this.attacks.filter(attack => {
      return this.getDistanceToTarget() <= attack.range
    })
    
    if (availableAttacks.length > 0) {
      // 随机选择一个可用攻击
      const randomIndex = Math.floor(Math.random() * availableAttacks.length)
      this.currentAttack = availableAttacks[randomIndex]
      this.attackDurationTimer = this.currentAttack.duration
      this.attackCooldownTimer = this.currentAttack.cooldown
    }
  }
  
  /**
   * 执行攻击
   */
  private executeAttack(deltaTime: number): void {
    if (!this.currentAttack || !this.target) return
    
    switch (this.currentAttack.pattern) {
      case AttackPattern.PROJECTILE:
        this.executeProjectileAttack()
        break
      case AttackPattern.CHARGE:
        this.executeChargeAttack()
        break
      case AttackPattern.AREA:
        this.executeAreaAttack()
        break
      case AttackPattern.SUMMON:
        this.executeSummonAttack()
        break
    }
  }
  
  /**
   * 执行弹幕攻击
   */
  private executeProjectileAttack(): void {
    if (!this.currentAttack || !this.target) return
    
    const attack = this.currentAttack
    const projectileCount = attack.projectileCount || 1
    const speed = attack.projectileSpeed || 200
    
    // 计算向目标的方向
    const dx = this.target.x - this.x
    const dy = this.target.y - this.y
    const distance = Math.sqrt(dx * dx + dy * dy)
    const dirX = dx / distance
    const dirY = dy / distance
    
    // 创建弹幕
    for (let i = 0; i < projectileCount; i++) {
      const angle = (i - (projectileCount - 1) / 2) * 0.2 // 扇形发射
      const cos = Math.cos(angle)
      const sin = Math.sin(angle)
      
      const projectile = new BossProjectile({
        x: this.x + this.width / 2,
        y: this.y + this.height / 2,
        width: 10,
        height: 10,
        velocity: {
          x: (dirX * cos - dirY * sin) * speed,
          y: (dirX * sin + dirY * cos) * speed
        },
        damage: attack.damage,
        lifeTime: 3000 // 3秒生命周期
      })
      
      this.projectiles.push(projectile)
    }
  }
  
  /**
   * 执行冲撞攻击
   */
  private executeChargeAttack(): void {
    if (!this.target) return
    
    // 快速冲向目标
    const dx = this.target.x - this.x
    const direction = Math.sign(dx)
    this.velocity.x = this.moveSpeed * 2 * direction // 冲撞时速度翻倍
  }
  
  /**
   * 执行范围攻击
   */
  private executeAreaAttack(): void {
    // 范围攻击的实现（这里简化为创建多个弹幕）
    const projectileCount = 8
    const speed = 150
    
    for (let i = 0; i < projectileCount; i++) {
      const angle = (i / projectileCount) * Math.PI * 2
      const dirX = Math.cos(angle)
      const dirY = Math.sin(angle)
      
      const projectile = new BossProjectile({
        x: this.x + this.width / 2,
        y: this.y + this.height / 2,
        width: 8,
        height: 8,
        velocity: {
          x: dirX * speed,
          y: dirY * speed
        },
        damage: this.currentAttack?.damage || 1,
        lifeTime: 2000
      })
      
      this.projectiles.push(projectile)
    }
  }
  
  /**
   * 执行召唤攻击
   */
  private executeSummonAttack(): void {
    // 召唤攻击的实现（这里简化处理）
    console.log('Boss执行召唤攻击')
  }
  
  /**
   * 更新弹幕
   */
  private updateProjectiles(deltaTime: number): void {
    for (let i = this.projectiles.length - 1; i >= 0; i--) {
      const projectile = this.projectiles[i]
      projectile.update(deltaTime)
      
      if (projectile.shouldBeRemoved()) {
        this.projectiles.splice(i, 1)
      }
    }
  }
  
  /**
   * 检查阶段转换
   */
  private checkPhaseTransition(): void {
    const healthPercent = this.health / this.maxHealth
    
    for (let i = this.currentPhase + 1; i < this.phases.length; i++) {
      if (healthPercent <= this.phases[i].healthThreshold) {
        this.enterPhase(i)
        break
      }
    }
  }
  
  /**
   * 进入新阶段
   */
  private enterPhase(phaseIndex: number): void {
    if (phaseIndex >= this.phases.length) return
    
    this.currentPhase = phaseIndex
    const phase = this.phases[phaseIndex]
    
    // 应用阶段修饰符
    this.moveSpeed *= phase.moveSpeedMultiplier
    
    // 添加新攻击模式
    if (phase.newAttacks) {
      this.attacks.push(...phase.newAttacks)
    }
    
    console.log(`Boss进入第${phaseIndex + 1}阶段`)
  }
  
  /**
   * 更新视觉效果
   */
  private updateVisualEffects(deltaTime: number): void {
    // 受击闪烁效果
    if (this.hitFlashTimer > 0) {
      this.visible = Math.floor(this.hitFlashTimer / 50) % 2 === 0
    } else {
      this.visible = true
    }
  }
  
  /**
   * 获取默认生命值
   */
  private getDefaultHealth(): number {
    switch (this.bossType) {
      case BossType.GUARDIAN:
        return 100
      case BossType.DESTROYER:
        return 150
      case BossType.PHANTOM:
        return 80
      default:
        return 100
    }
  }
  
  /**
   * 获取默认移动速度
   */
  private getDefaultMoveSpeed(): number {
    switch (this.bossType) {
      case BossType.GUARDIAN:
        return 50
      case BossType.DESTROYER:
        return 30
      case BossType.PHANTOM:
        return 80
      default:
        return 50
    }
  }
  
  /**
   * 获取默认攻击模式
   */
  private getDefaultAttacks(): BossAttack[] {
    switch (this.bossType) {
      case BossType.GUARDIAN:
        return [
          {
            pattern: AttackPattern.PROJECTILE,
            damage: 1,
            cooldown: 2000,
            range: 300,
            duration: 500,
            projectileSpeed: 200,
            projectileCount: 1
          }
        ]
      case BossType.DESTROYER:
        return [
          {
            pattern: AttackPattern.CHARGE,
            damage: 2,
            cooldown: 3000,
            range: 200,
            duration: 1000
          },
          {
            pattern: AttackPattern.AREA,
            damage: 1,
            cooldown: 4000,
            range: 250,
            duration: 800
          }
        ]
      case BossType.PHANTOM:
        return [
          {
            pattern: AttackPattern.PROJECTILE,
            damage: 1,
            cooldown: 1500,
            range: 400,
            duration: 300,
            projectileSpeed: 300,
            projectileCount: 3
          }
        ]
      default:
        return []
    }
  }
  
  /**
   * 初始化阶段系统
   */
  private initializePhases(thresholds?: number[]): BossPhase[] {
    const defaultThresholds = thresholds || [0.7, 0.4, 0.1]
    
    return defaultThresholds.map((threshold, index) => ({
      healthThreshold: threshold,
      moveSpeedMultiplier: 1 + index * 0.2, // 每阶段速度增加20%
      attackCooldownMultiplier: 1 - index * 0.1, // 每阶段攻击冷却减少10%
      specialBehavior: `phase_${index + 1}`
    }))
  }
  
  /**
   * 渲染Boss（重写以添加特殊效果）
   */
  render(ctx: CanvasRenderingContext2D): void {
    if (!this.visible) return
    
    // 绘制Boss本体
    super.render(ctx)
    
    // 绘制生命值条
    this.renderHealthBar(ctx)
    
    // 绘制弹幕
    this.projectiles.forEach(projectile => projectile.render(ctx))
    
    // 绘制状态指示器
    this.renderStateIndicator(ctx)
  }
  
  /**
   * 渲染生命值条
   */
  private renderHealthBar(ctx: CanvasRenderingContext2D): void {
    const barWidth = this.width
    const barHeight = 8
    const barX = this.x
    const barY = this.y - 15
    
    // 背景
    ctx.fillStyle = '#333333'
    ctx.fillRect(barX, barY, barWidth, barHeight)
    
    // 生命值
    const healthPercent = this.health / this.maxHealth
    ctx.fillStyle = healthPercent > 0.5 ? '#4CAF50' : healthPercent > 0.25 ? '#FF9800' : '#F44336'
    ctx.fillRect(barX, barY, barWidth * healthPercent, barHeight)
    
    // 边框
    ctx.strokeStyle = '#000000'
    ctx.lineWidth = 1
    ctx.strokeRect(barX, barY, barWidth, barHeight)
  }
  
  /**
   * 渲染状态指示器
   */
  private renderStateIndicator(ctx: CanvasRenderingContext2D): void {
    let color = '#FFFFFF'
    
    switch (this.state) {
      case BossState.IDLE:
        color = '#9E9E9E'
        break
      case BossState.PATROL:
        color = '#2196F3'
        break
      case BossState.CHASE:
        color = '#FF9800'
        break
      case BossState.ATTACK:
        color = '#F44336'
        break
      case BossState.STUNNED:
        color = '#9C27B0'
        break
      case BossState.DEFEATED:
        color = '#424242'
        break
    }
    
    // 绘制状态指示圆点
    ctx.fillStyle = color
    ctx.beginPath()
    ctx.arc(this.x + this.width - 10, this.y + 10, 5, 0, Math.PI * 2)
    ctx.fill()
  }
  
  /**
   * 获取默认颜色
   */
  protected getDefaultColor(): string {
    switch (this.bossType) {
      case BossType.GUARDIAN:
        return '#795548' // 棕色
      case BossType.DESTROYER:
        return '#D32F2F' // 深红色
      case BossType.PHANTOM:
        return '#7B1FA2' // 紫色
      default:
        return '#424242' // 深灰色
    }
  }
}

/**
 * BossProjectile - Boss弹幕类
 */
export interface BossProjectileOptions {
  x: number
  y: number
  width: number
  height: number
  velocity: Vector2D
  damage: number
  lifeTime: number
}

export class BossProjectile extends Entity {
  public damage: number
  private lifeTime: number
  private age: number = 0
  
  constructor(options: BossProjectileOptions) {
    super({
      id: `projectile_${Date.now()}_${Math.random()}`,
      x: options.x,
      y: options.y,
      width: options.width,
      height: options.height,
      type: EntityType.PROJECTILE,
      velocity: options.velocity
    })
    
    this.damage = options.damage
    this.lifeTime = options.lifeTime
  }
  
  /**
   * 更新弹幕
   */
  update(deltaTime: number): void {
    if (!this.active) return
    
    // 更新年龄
    this.age += deltaTime
    
    // 检查生命周期
    if (this.age >= this.lifeTime) {
      this.destroy()
      return
    }
    
    // 应用物理
    this.applyPhysics(deltaTime)
    
    // 检查边界（超出屏幕则销毁）
    if (this.x < -100 || this.x > 900 || this.y < -100 || this.y > 700) {
      this.destroy()
    }
  }
  
  /**
   * 获取默认颜色
   */
  protected getDefaultColor(): string {
    return '#FF5722' // 橙红色弹幕
  }
}